/* 
    Project     : 48c6c450f1a4a0cc53d9585dc0fee742
    Created on  : Mar 16, 2013, 11:29:15 PM
    Author      : Truong Khuong - khuongxuantruong@gmail.com
    Description :
        Purpose of the stylesheet follows.
*/
var GALLERY_CONFIG={
    JQXGRID_ELEMENT     :   '#jqxGrid_Backend_Categories',
    CATE_PARENT           :   '',
    BINDING_URI         :   base_url+'backend/wallpaper/binding/',
    EDIT_PANEL_URI      :   base_url+"backend/wallpaper/EditPanel",
    EDIT_PANEL_URI2      :   base_url+"backend/wallpaper/EditPanelIn",
    COMMIT_URI          :   base_url+"backend/wallpaper/Commit",
    DELETE_URI          :   base_url+"backend/excution/delete/gallery/album/albu",
    PENDING             : false
};
var _GALLERY=(function(){
    var init=false;
    var datafields=[
        { name  :   'albu_id' ,type :   'int'},
        { name  :   'albu_fcate' },
        { name  :   'albu_title' ,type:'string'},
        { name  :   'albu_alias' },
        { name  :   'albu_position',type    :   'int' },
        { name  :   'albu_status', type : 'bool' },
        { name  :   'albu_insert' },
        { name  :   'albu_update' }
    ],
    getEditorDataAdapter = function (datafield) {
        var source =
         {
                localdata: GALLERY_CONFIG.KITCHEN_CATES_DATA,
                datatype: "array",
//                datatype: "json",type : "POST",
//                datafields: datafields,
//                id: 'cate_id',
//                url: base_url+'backend/category/binding/kitchen',
//                root        : 'rows',
//                beforeprocessing: function(data){ source.totalrecords = data.total_rows; },
                datafields:
                [
                    { name: 'cate_id', type: 'string' },
                    { name: 'cate_title', type: 'string' }
                ]
         };
        var dataAdapter = new $.jqx.dataAdapter(source, { uniqueDataFields: [datafield] });
        return dataAdapter;
    },
    columns=[
        { text: 'Title'     , dataField: 'albu_title'       , filtertype: 'textbox' },
        { text: 'Kitchen Category'     , dataField: 'albu_fcate'     ,width:320,filterable:false ,
            columntype: 'template',
            cellsrenderer:function (row, column, value) {
                var str='<div style="overflow: hidden; text-overflow: ellipsis; padding-bottom: 2px; text-align: left; margin-right: 2px; margin-left: 4px; margin-top: 3px;">';
                if(value && value!=""){
                    value=value.split(',');
                    for(var i=0;i<value.length;i++){
                        str+="<span class='label label-info'>"+GALLERY_CONFIG.KITCHEN_CATES[value[i]]+"</span>&nbsp;";
                    }
                    
                }
                str+='</div>';
                return str;
            },
            createeditor: function (row, cellvalue, editor, cellText, width, height) {
                          // construct the editor. 
                editor.jqxDropDownList({
                    checkboxes: true, source: getEditorDataAdapter('cate_id'), displayMember: 'cate_title', valueMember: 'cate_id', width: width, height: height, theme: theme,
                    selectionRenderer: function () {
                        return "Please Choose:";
                    }
                });
            },
            initeditor: function (row, cellvalue, editor, celltext, pressedkey) {
                // set the editor's current value. The callback is called each time the editor is displayed.
                var items = editor.jqxDropDownList('getItems');
                editor.jqxDropDownList('uncheckAll');
                var values = cellvalue.split(/,\s*/);
                for (var j = 0; j < values.length; j++) {
                    for (var i = 0; i < items.length; i++) {
                        if (items[i].value === values[j]) {
                            editor.jqxDropDownList('checkIndex', i);
                        }
                    }
                }
            },
            geteditorvalue: function (row, cellvalue, editor) {
                // return the editor's value.
                return editor.val();
            }
        },
        { text: 'Position'  , dataField: 'albu_position'    ,width:80,filterable:false, cellsalign:'right',columntype:'numberinput',filtertype:'number'},
        { text: 'Status'    , dataField: 'albu_status'      ,width:80,filterable:false ,columntype:'checkbox',threestatecheckbox:false,filtertype:'bool'},
        { text: 'Insert'    , dataField: 'albu_insert'      ,width:120,filterable:false ,cellsformat:'yyyy-MM-dd HH:mm:ss', editable:false},
        { 
            text: '#'        , dataField: 'albu_id'          ,width:60,filterable:false ,sortable: false,
            editable:false,
            cellsrenderer : function (row, column, value) {
                var str="<span style='margin: 6px; float: left;'>";
                if(value && value>0){
                    try{
                        //value = $.parseJSON(value);
                        str+="\
                            <span onclick=\"_GALLERY.EditItemIn('"+value+"');\" \
                             title='Edit'><img src=\"/libraries/images/16/edit_black.png\"/></span>\
                        ";
                        str+="\
                            <span onclick=\"_GALLERY.DeleteItem('"+value+"');\" \
                             title='Delete'><img src=\"/libraries/images/16/delete_black.png\"/></span>\
                        ";
                    }catch(e){}
                }
                str+="</span>";
                return str;
            }
        },
    ],
    source,dataAdapter,
    grid_element=GALLERY_CONFIG.JQXGRID_ELEMENT;
    var initrowdetails=function (index, parentElement, gridElement, datarecord) {
        var tabsdiv = null;
        $(parentElement).html(datarecord.albu_title)
        if (tabsdiv != null) {

        }
    };
    
    
    return {
        OnInit:function(){
            try{
                if(init) return;
                init=true;
                //grid_element=$('#jqxGrid_Backend_Categories');
                
                
                source ={
                    datatype: "json",type : "POST",
                    datafields: datafields,
                    url: GALLERY_CONFIG.BINDING_URI,
                    filter      : function(){ $(GALLERY_CONFIG.JQXGRID_ELEMENT).jqxGrid('updatebounddata', 'filter'); },
                    sort        : function(){ $(GALLERY_CONFIG.JQXGRID_ELEMENT).jqxGrid('updatebounddata'); },
                    root        : 'rows',
                    beforeprocessing: function(data){ 
                        data.rows=data.data.rows;
                        source.totalrecords = data.data.total_rows; 
                    }
                };
                dataAdapter = new $.jqx.dataAdapter(source, {
                    loadError: function(xhr, status, error){
                        bootbox.modal("<b>Status</b>:"+xhr.status+"<br/><b>ThrownError</b>:"+error+"<br/>", 'Error Message!');
                    }
                });
                $(GALLERY_CONFIG.JQXGRID_ELEMENT).jqxGrid({
                    rendergridrows: function(obj){
                        return obj.data;    
                    },ready: function () {
                        _GALLERY.Filter('albu_fcate',GALLERY_CONFIG.CATE_PARENT);
                        
                    },
                    width: '100%',//autoheight:true,
                    source: dataAdapter,
                    theme: theme,sortable: true,
                    //filterable: true,
                    //autoshowfiltericon: true,
                    //showfilterrow: true,
                    rowdetails: true,
                    editable: true,
                    rowdetailstemplate: { rowdetails: "<div style='margin: 2px;'>Loading...</div>",rowdetailsheight:200},
                    initrowdetails: initrowdetails,
                    //rowsheight:34,
                    showemptyrow: true,
                    virtualmode:false,
                    columns: columns
                });
                
                

            }catch(e){
                bootbox.alert(e.message);
            }
        },
        AddItem:function(){
            this.EditItem(0);
        },
        AddItemIn:function(){
            this.EditItemIn(0);
        },
        EditItem:function(Id){
            if($('#_form_edit_panel').length==1)return;
            if(PENDING) return false;
            var kcgl=$('"<div id=\'kitchen_botbox_gallery\'>Loading...</div>"');
            bootbox.dialog({
                backdrop:true,
                animate:false,
                message: kcgl,
                title: "Kitchen Album",
                buttons: {
                    save: {
                        label: "Save",
                        className: "btn-success",
                        callback: function() {
                            return _GALLERY.Save();
                        }
                    },
                    cancel: {
                        label: "Cancel",
                        className: "btn-danger",
                        callback: function() {
                            
                        }
                    }
                }
            });
            new backend({
                url         :   GALLERY_CONFIG.EDIT_PANEL_URI,
                data        :   {
                    Id      :   Id,
                    CateId    :   GALLERY_CONFIG.CATE_PARENT
                },
                callback    :   function(rsdata){
                    PENDING=false;
                    if(rsdata.result<0){
                        kcgl.html(rsdata.message);
                    }else{
                        kcgl.html(rsdata.message);
                        //$(".collapse").collapse();
//                        $('#_edit_panel_tabs').jqxTabs({
//                            theme: 'metro', height: 'auto',  scrollable: true, 
//                            selectionTracker: true, animationType: 'fade'
//                        });
                        $('#albu_fcate').selectpicker({cls:'btn-sm'});
                        //$('#albu_fcate').select2();
                    }
                }
            }).call();
        },
        EditItemIn:function(Id){
            
            if($('#_form_edit_panel').length==1)return;
            if(PENDING) return false;
            new backend({
                url         :   GALLERY_CONFIG.EDIT_PANEL_URI2,
                data        :   {
                    Id      :   Id,
                    CateId    :   GALLERY_CONFIG.CATE_PARENT
                },
                callback    :   function(rsdata){
                    PENDING=false;
                    if(rsdata.result<0){
                        $('#_edit_panel_insite').html(rsdata.message).show();
                    }else{
                        $('#viewport_gallery').hide();
                        $('#_edit_panel_insite').show().html(rsdata.message);
                        //$(".collapse").collapse();
//                        $('#_edit_panel_tabs').jqxTabs({
//                            theme: 'metro', height: 'auto',  scrollable: true, 
//                            selectionTracker: true, animationType: 'fade'
//                        });
                        $('#albu_fcate').selectpicker({cls:'btn-sm'});
                        //$('#albu_fcate').select2();
                    }
                }
            }).call();
        },
        Save:function(){
            //if(GALLERY_CONFIG.PENDING) return false;
            var Params=$('#_form_edit_panel').serializeObject();
            //Params.cate_type=GALLERY_CONFIG.CATE_PARENT;
            
            var imgs=new Array();
            imgs=$('#_form_edit_panel .album_images img.album-item').map(function(){
                return this.src;
            });
            Params.albu_images=new Array();
            for(var i=0;i<imgs.length;i++){
                Params.albu_images[i]=imgs[i];
                
            }
            GALLERY_CONFIG.PENDING=true;
            new backend({
                url         :   GALLERY_CONFIG.COMMIT_URI,
                data        :   {
                    Params  :   Params,
                    Id      :   $('#albu_id').val()
                },
                callback    :   function(rsdata){
                    GALLERY_CONFIG.PENDING=false;
                    if(rsdata.result<0){
                        bootbox.alert(rsdata.message);
                        return false;
                    }else{
                        //bootbox.alert(rsdata.message);
                        _GALLERY.Cancel();
                        _GALLERY.Refresh();
                        return true;
                    }
                }
            }).call();
            return false;
        },
		SaveIn:function(){
            //if(GALLERY_CONFIG.PENDING) return false;
            var Params=$('#_form_edit_panel').serializeObject();
            //Params.cate_type=GALLERY_CONFIG.CATE_PARENT;
            
            var imgs=new Array();
            imgs=$('#_form_edit_panel .album_images img.album-item').map(function(){
                return this.src;
            });
            Params.albu_images=new Array();
            for(var i=0;i<imgs.length;i++){
                Params.albu_images[i]=imgs[i];
                
            }
            GALLERY_CONFIG.PENDING=true;
            new backend({
                url         :   GALLERY_CONFIG.COMMIT_URI,
                data        :   {
                    Params  :   Params,
                    Id      :   $('#albu_id').val()
                },
                callback    :   function(rsdata){
                    GALLERY_CONFIG.PENDING=false;
                    if(rsdata.result<0){
                        bootbox.alert(rsdata.message);
                        return false;
                    }else{
                        //bootbox.alert(rsdata.message);
                        _GALLERY.CancelIn();
                        _GALLERY.Refresh();
                        return true;
                    }
                }
            }).call();
            return false;
        },
		OtherAdvand:function(){
			$('.otheradvand').toggle();
		},
        Cancel:function(){
            $('#_form_edit_panel').parents('.bootbox').modal('hide');
        },
        CancelIn:function(){
            $('#viewport_gallery').show();
            $('#_edit_panel_insite').hide().html('');
        },
        DeleteItem:function(id){
			ConfirmMsg(function(){
				backend_delete('album','album','albu',id,function(){
                    $(GALLERY_CONFIG.JQXGRID_ELEMENT).jqxGrid('updatebounddata');
                    NoticeMsg("Success ! Item have been Deleted.");
                });
			},'These items will be permanently deleted and cannot be recovered. Are you sure ?')
			return;
            bootbox.confirm("These items will be permanently deleted and cannot be recovered. Are you sure ?", function(result) {
                if(!result) return;
                backend_delete('album','album','albu',id,function(){
                    $(GALLERY_CONFIG.JQXGRID_ELEMENT).jqxGrid('updatebounddata');
                    Example.show("Success ! Item have been Deleted.");
                });
            });
			
        },
        RestoreItem:function(){
            accessdenied();
        },
        Permission:function(id){
            
        },
        PrivateItem:function(){
            accessdenied();
        },
        Setting:function(){
            bckdialog({
                message:$('#window-sOpt'),
                icon:"<img class='p-a t-7 l-8' src='"+base_url+"/libraries/images/16/option.gif'/>",
                title:'Setting'
            }).open();
        },
        Refresh:function(){
            $(GALLERY_CONFIG.JQXGRID_ELEMENT).jqxGrid('updatebounddata');
            //Msg('✔ Dép bông nhung mềm mịn - 68.000 | Bộ màu vẽ 68 món - 85.000 | Máy uốn tóc new - 135.000');
        },
        Filter:function(datafield,filtervalue){
            GALLERY_CONFIG.CATE_PARENT=filtervalue;
            var filtertype = 'stringfilter';
            var filtergroup = new $.jqx.filter();
            var filter_or_operator = 1;
            var filtercondition = 'contains';
            var filter = filtergroup.createfilter(filtertype, filtervalue, filtercondition);
            filtergroup.addfilter(filter_or_operator, filter);
            
            //$(grid_element).jqxGrid('clearfilters');
            // add the filters.
            $(GALLERY_CONFIG.JQXGRID_ELEMENT).jqxGrid('addfilter', datafield, filtergroup);
            // apply the filters.
            $(GALLERY_CONFIG.JQXGRID_ELEMENT).jqxGrid('applyfilters');
        },
        ChooseImages:function(){
            openKCFinderMulti(function(files){
                var str='';
                for (var i = 0; i < files.length; i++){
                    if($('.thumbnail').length+i>=5)break;
                    str += '<div class="col-sm-3 col-xs-6 col-md-3 span2">\
                                <div class="thumbnail widget" style="position: relative">\
                                    <div class="well">\
						    <div class="view">\
                                    <button type="button" class="close" aria-hidden="true" \
                                        style="font-family: tahoma;font-size: 16px;position: absolute;top: 0;right: 0"><img onclick="_GALLERY.ChooseImages()" width="16" style="margin-top: 0px;" src="/libraries/images/16/keyamoon/delete.png"></button>\
                                    <img class="album-item" data-src="holder.js/300x200" src="'+files[i]+'" alt="...">\
                                </div></div></div>\
                            </div>' + "\n";
                }
                $('.album_images').append(str);
            });

        }
    };
}());
$(document).ready(function () {
    //Btree().Init();
});